<template>
  <div>
    <!-- 搜索结果页-头部导航 -->
    <div class="search-result-container">
      <!-- 点击实现后退效果 -->
      <van-nav-bar
        title="搜索结果"
        left-arrow
        @click-left="$router.go(-1)"
        fixed
      />
    </div>
    <van-list
      v-model="loading"
      :finished="finished"
      :immediate-check="false"
      finished-text="没有更多了"
      @load="onLoad"
      offset="50"
    >
      <ArticleItem
        v-for="item in articleList"
        :key="item.art_id"
        :item="item"
        :isShow="false"
        @click.native="toArticleDetail(item.art_id)"
      ></ArticleItem>
    </van-list>
  </div>
</template>

<script>
// 事件修饰符.native ->给组件内根标签，绑定原生click点击事件
// 业务:
// 前端(自己）->后端(自己)
// 后端保存文章的数据，文章里的图片来自于其他服务器路径cnblog(图片第三方的)//后端只是保存了图片的地址
// 后端会把数据和图片地址返回给前端，前端铺设页面，用img标签-〉第三方图片(404/403) - (人家把图片删除了)
import { searchResultAPI } from '@/api/index.js'
import ArticleItem from '@/components/ArticleItem.vue'
export default {
  name: 'SeachResult',
  components: {
    ArticleItem
  },
  data() {
    return {
      page: 1,
      articleList: [], // 文章列表
      loading: false,
      finished: false
    }
  },
  created() {
    this.getSearchResult()
  },
  methods: {
    async getSearchResult() {
      const res = await searchResultAPI({
        page: this.page,
        q: this.$route.params.keywords
      })
      if (res.data.data.results.length === 0) {
        this.finished = true
        return
      }
      this.articleList = [...this.articleList, ...res.data.data.results]
    },
    onLoad() {
      if (this.articleList.length > 0) {
        this.page++
        this.getSearchResult()
        this.loading = false
      }
    },
    // 跳转文章详情
    toArticleDetail(id) {
      this.$router.push({
        path: `/detail?art_id=${id}`
      })
    }
  }
}
</script>

<style lang="less" scoped>
.search-result-container {
  padding-top: 46px;
}
</style>
